<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>学生成绩管理系统</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="student.css">
</head>
<body>
<div class="layout">
  <!-- 侧边栏 -->
  <nav class="sidebar">
    <div class="sidebar-title">学生成绩管理系统</div>
    <div class="sidebar-menu">
      <a href="student_course.html">我的课程</a>
      <a href="student_score.html">我的成绩</a>
      <a class="active" href="student_chooseCourse.html">选课</a>
      <a href="student_deleteCourse.html">退课</a>
    </div>
    <div class="sidebar-logout">退出登录</div>
  </nav>
  <!-- 主内容区 -->
  <div class="main">
    <div class="header">
      <span class="header-title">学生成绩管理系统</span>
      <span class="header-user" id="username"></span>
    </div>
    <div class="content">
      <div class="decoration-yellow"></div>
      <div class="decoration-red"></div>
      <div class="decoration-green"></div>

      <div class="actions-bar">
        <input class="search-input" placeholder="课程名" id="search-course" />
        <input class="search-input" placeholder="教师姓名" id="search-teacher" />
        <button class="btn btn-info" id="search-btn">🔍</button>
      </div>

      <div class="course-list" id="course-list">
          <div class="course-info">
          </div>
        </a>
      </div>
    </div>
  </div>
</div>
<script>
let allCourses = [];    // 所有课程数据
  let selectedCourses = new Set();  // 已选择课程的课程号

  // 拉取“我的选课”记录，获得已选课程号
  function fetchSelectedCourses() {
    return fetch('/course/query')
      .then(res => res.json())
      .then(data => {
        selectedCourses = new Set(data.map(item => item.Cno));
      });
  }

  // 拉取所有可选课程
  function fetchAllCourses() {
    return fetch('/course/query')
      .then(res => res.json())
      .then(data => {
        allCourses = data || [];
      });
  }

  // 渲染课程卡片
function renderCourses(courseArr) {
  const courseList = document.getElementById('course-list');
  courseList.innerHTML = '';
  if (!courseArr.length) {
    courseList.innerHTML = '<div style="color:#bbb;padding:30px 0;">暂无课程</div>';
    return;
  }

  courseArr.forEach(course => {
    // 判断是否已选
    const isChosen = selectedCourses.has(course.Cno);

    // 处理简介截断
    const fullDesc = course.courseDesc || '';
    const shortDesc = fullDesc.length > 15 ? fullDesc.slice(0, 15) + '...' : fullDesc;

   const card = document.createElement('a');
card.className = 'course-card';
card.href = 'student_courseDescription.html';
card.style = 'text-decoration: none; color: inherit;';
card.onclick = function () {
  sessionStorage.setItem('selectedCourse', JSON.stringify(course));
};
card.innerHTML = `
<a href="student_courseDescription.html" class="course-card" style="display: flex; text-decoration: none; color: inherit;">
  <div class="course-info">
    <div class="course-title">${course.Cname} - ${course.tname}</div>
    <div class="course-desc">${course.Cno}</div>
    <div class="course-desc">${shortDesc}</div>
    <div class="course-small">${course.created_at}</div>
    <button
      class="btn choose-btn"
      style="pointer-events: auto;${isChosen ? 'background:#ccc;cursor:not-allowed;' : ''}"
      ${isChosen ? 'disabled' : ''}
      data-courseNumber="${course.Cno}"
      onclick="event.stopPropagation(); chooseCourse('${course.Cno}', this);"
    >${isChosen ? '已选' : '选课'}</button>
  </div>
`;

    courseList.appendChild(card);
  });

  // 给所有“选课”按钮绑定事件
  document.querySelectorAll('.course-card .btn:not([disabled])').forEach(btn => {
    btn.onclick = function() {
      const Cno = this.getAttribute('data-Cno');
      chooseCourse(Cno, this);
    };
  });
}


  // 选课操作
  function chooseCourse(Cno, btn) {
    btn.disabled = true;
    btn.textContent = '处理中...';
    btn.style.background = '#8ec2ff';
    fetch('/student/courses', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ Cno })
    })
    .then(res => res.json())
    .then(result => {
      if (result && result.success !== false) {
        selectedCourses.add(Cno);
        btn.textContent = '已选';
        btn.style.background = '#ccc';
      } else {
        btn.disabled = false;
        btn.textContent = '选课';
        btn.style.background = '';
        alert(result.message || '选课失败');
      }
    })
    .catch(() => {
      btn.disabled = false;
      btn.textContent = '选课';
      btn.style.background = '';
      alert('选课失败，请重试');
    });
  }

  // 搜索功能
  function filterAndRenderCourses() {
    const courseKeyword = document.getElementById('search-course').value.trim();
    const teacherKeyword = document.getElementById('search-teacher').value.trim();
    const filtered = allCourses.filter(course => {
      return (!courseKeyword || course.Cname.includes(courseKeyword))
        && (!teacherKeyword || course.teacherName.includes(teacherKeyword));
    });
    renderCourses(filtered);
  }

  document.getElementById('search-btn').onclick = filterAndRenderCourses;
  
 /*  // 支持回车键搜索
  document.getElementById('search-course').addEventListener('keyup', function(e){
    if (e.key === 'Enter') filterAndRenderCourses();
  });
  document.getElementById('search-teacher').addEventListener('keyup', function(e){
    if (e.key === 'Enter') filterAndRenderCourses();
  });
 */
const userId = sessionStorage.getItem('user_id');  // 登录后记录的用户ID

fetch('/student/courses', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify([{ studentId: parseInt(userId), courseId: parseInt(Cno) }])
})


   document.addEventListener('DOMContentLoaded', function () {
    const userId = sessionStorage.getItem('user_id');
    fetch('/student/{user_id}')
    .then(res => res.json())
    .then(user => {
      // 假如后端返回 Sname 字段
      document.getElementById('username').textContent = res.data.sname + "【学生】";
    })
    .catch(() => {
      document.getElementById('username').textContent = "未登录【学生】";
    });
});
  // 初始化
  document.addEventListener('DOMContentLoaded', async function() {
    await fetchSelectedCourses();
    await fetchAllCourses();
    filterAndRenderCourses();
  });
</script>
</body>
</html>